package com.smq.chatserver.controller;

import com.smq.chatserver.bean.Result;
import com.smq.chatserver.bean.Teem;
import com.smq.chatserver.bean.TeemMember;
import com.smq.chatserver.bean.TeemQueryResult;
import com.smq.chatserver.services.TeemMemberService;
import com.smq.chatserver.services.TeemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Api(tags = "群组模块")
@RestController
@RequestMapping("/teem")
public class TeemController {

    @Autowired
    private TeemService teemService;

    @Autowired
    private TeemMemberService teemMemberService;

    @ApiOperation(value = "查询群组信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ope", value = "群聊"),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "header")
    })
    @PostMapping("/query")
    public Result<List<TeemQueryResult>> query(Integer ope, @RequestHeader String userId) {
        ArrayList<TeemQueryResult> teemQueryResults = new ArrayList<>();
        List<Teem> teems = teemService.query(userId);
        for (Teem teem : teems) {
            List<TeemMember> mappers = teemMemberService.query(teem.getId());
            teemQueryResults.add(new TeemQueryResult(teem, mappers));
        }
        return Result.success(teemQueryResults);
    }

    @ApiOperation(value = "创建群组")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "群聊", required = true),
            @ApiImplicitParam(name = "members", value = "群成员列表", required = true),
            @ApiImplicitParam(name = "iconUri", value = "群头像", required = true),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "header")
    })
    @PostMapping("/create")
    public Result<TeemQueryResult> create(String name, @RequestParam List<String> members, String iconUri, @RequestHeader String userId) {
        Teem teem = teemService.create(name, iconUri, userId);
        ArrayList<TeemMember> teemMembers = new ArrayList<>();
        for (String member : members) {
            TeemMember teemMember = teemMemberService.create(teem.getId(), member, name, 0);
            teemMembers.add(teemMember);
        }
        return Result.success(new TeemQueryResult(teem, teemMembers));
    }
}
